import time

import requests
from werkzeug.utils import redirect

from util.captcha.captcha import captcha
from util.myjwt import myjwt
from views.base import BaseHandler
import json,re
from db import db
from util.myredis import r
from util.Smssdk import send_message

class Imagecode(BaseHandler):
    def get(self):
        # 调用 captcha生成图片验证码
        # name,text,img = captcha.generate_captcha()
        # r.str_setex(uuid,text,100)
        # res = make_response(img)
        # res.headers['Content-Type'] = 'image/jpg'
        # return self.write(res)
        #     信息   流
        name, text, img = captcha.generate_captcha()
        uuid = self.get_query_argument('uuid')
        r.str_add(uuid,text)
        print(text)
        self.set_header('Content-Type', 'image/jpg')
        self.write(img)



class Sendsms(BaseHandler):
    def post(self):
        ip = self.request.remote_ip
        # 根据ip地址获取值
        key = ip + 'iplist'
        cip  = r.get_all_hash(key)
        print(cip)
        # if cip == {}:
        #     print('12132')
        #     r.del_hash(key, 'count')
        #
        #     r.insert_hash(key, 'time', int(time.time()))
        #     r.insert_hash(key, 'count', 1)
        if cip:
            t = r.get_value_hash(key,'time')
            if int(time.time()) - int(t) >60:
                r.del_key(key)
                r.insert_hash(key, 'time', int(time.time()))
                r.insert_hash(key, 'count', 1)
                # return self.finish({'code':400,'msg':'时间过期'})
            else:
                count = r.get_value_hash(key,'count')
                print(count.decode())
                if int(count.decode())>2:
                    return self.finish({'code':401,'msg':'一分只能发送三次'})
                else:
                    r.hincrbyset(key,'count',1)
        else:
            r.insert_hash(key,'time',int(time.time()))
            r.insert_hash(key,'count',1)
        data = json.loads(self.request.body)
        mobile = data['mobile']
        uuid = data['uuid']
        imagecode = data['imagecode']
        if not all([mobile,uuid,imagecode]):
            return self.finish({'code':20010,'msg':'参数不完整'})
        if not re.match(r'^1[35678]\d{9}$',mobile):
            return self.finish({'code':200,'msg':'手机号格式有误'})
        code = r.str_get(uuid)
        if code:
            if imagecode.lower() != code.decode().lower():
                return self.finish({'code':2011,'msg':'图片验证码错误'})
            r.del_key(uuid)
        else:
            return self.finish({'code':200,'msg':'图片验证码不存在'})
        v = r.str_get(mobile)
        if v:
            return self.finish({'code':20012,'msg':'一分钟只能发一次'})
        c = send_message(mobile)
        print(c)
        return self.finish({'code':200,'msg':'发送成功'})
class Pclogin(BaseHandler):
    def post(self):
        data = self.request.body
        mes = json.loads(data)
        mobile = mes['mobile']
        code = mes['code']
        codemes = r.str_get(mobile)
        if codemes:
            if str(codemes.decode()) != str(code):
                return self.finish({'coode':'10020','msg':'短信验证码错误'})
            r.del_key(mobile)
            sql = "select * from pcuser where mobile='%s'"%mobile
            user = db.findone(sql)
            if user:
                data = {'data': {'uid': user['id'], 'mobile': user['mobile'], 'exp': int(time.time())}}
                token = myjwt.jwt_encode(data)
                return self.finish({'code':200,'msg':'登录成功','uid':user['id'],'token':token})
            else:
                # return self.finish({'code':401,'msg':'未查找到此用户'})
                sql1 = "insert into pcuser(mobile) values('%s')"%mobile
                db.add(sql1)
                db.commit()
                return self.finish({'code':200,'msg':'注册成功'})
        else:
            return self.finish({'code':10021,'msg':'验证码过期'})


#微博登录
class wblogin(BaseHandler):
    def get(self):
        client_id = '3674019597'
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
        return self.write({"code": 200, "url": url})
class wbcallback(BaseHandler):
    def get(self):
        code = self.get_query_argument('code')
        # 向access_token接口发送post请求
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # 根据返回结果操作
        # 获取token和uid
        message = json.loads(res.text)
        token = message['access_token']
        uid = message['uid']
        # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
        sql = "select pcuser.id,pcuser.mobile from sf_login inner join pcuser on sf_login.userid=pcuser.id where sf_login.uid='%s'" % (
            str(uid))
        user = db.findone(sql)
        if user:
            # 生成jwt
            # 返回jwt token
            token = myjwt.jwt_encode(
                data={"data": {"uid": user['id'], "mobile": user['mobile'], 'exp': int(time.time())}})
            return self.redirect("http://localhost:8080/#/updateToken?token=" + token + "&userid=" + str(user['id']))
        else:
            # 绑定
            return self.redirect("http://localhost:8080/#/bangMobile?token=" + str(token) + "&uid=" + str(uid))
class BingMobile(BaseHandler):
    def post(self):
        # 接收参数
        data = json.loads(self.request.body)
        # 加入用户表
        sql = "insert into pcuser(mobile) values('%s')" % (data['mobile'])
        userid = db.add(sql)
        print('asohddddd',userid)
        # 加入三方登录表
        uid = data['uid']
        token = data['token']
        sql2 = "insert into sf_login(userid,webfrom,uid,token) values(%d,'weibo','%s','%s')" % (
            userid, int(uid), token)
        db.add(sql2)
        db.commit()
        # 返回jwt token
        token = myjwt.jwt_encode(data={"data": {"uid": userid, "mobile": data['mobile'], 'exp': int(time.time())}})
        return self.finish({"code": 200, "token": token, "userid": userid})